/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.woxthebox.draglistview.sample.adapter;

import com.woxthebox.draglistview.sample.ResourceTable;
import com.woxthebox.draglistview.sample.bean.ListBean;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;

import java.util.List;

/**
 * HorizontalItemAdapter第二级item适配器
 *
 * @since 2021-04-19
 */
public class HorizontalItemAdapter extends BaseItemProvider {
    private List<ListBean> list;
    private AbilitySlice slice;

    /**
     * HorizontalItemAdapter构造，需要传入数据源，AbilitySlice
     *
     * @param list
     * @param slice
     */
    public HorizontalItemAdapter(List<ListBean> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int id) {
        return id;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Component cpt;
        ViewHolder viewHolder;
        if (component == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_list_item_layout, null, false);
            viewHolder = new ViewHolder(component);
            cpt.setTag(viewHolder);
        } else {
            cpt = component;
            viewHolder = (ViewHolder) cpt.getTag();
        }
        viewHolder.image.setPixelMap(list.get(i).getImgId());
        viewHolder.text.setText(list.get(i).getValue());
        return cpt;
    }

    /**
     * 横向Item布局的ViewHolder
     *
     * @since 2021-04-19
     */
    private class ViewHolder {
        Image image;
        Text text;

        ViewHolder(Component component) {
            image = (Image) component.findComponentById(ResourceTable.Id_list_item_img);
            text = (Text) component.findComponentById(ResourceTable.Id_list_item_text);
        }
    }
}
